package com.woniu.scss.config;

import cn.hutool.core.util.ObjectUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/*
 * @Auther:吴兴龙
 * @Date:2023/7/6
 * @Description:
 */
@Configuration
public class FeignConfig implements RequestInterceptor {


    @Override
    public void apply(RequestTemplate requestTemplate) {

        // 获取到TOKEN
        ServletRequestAttributes attributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String token = request.getHeader("token");
        // 把token放在feign的头里面（增强feign功能）
        requestTemplate.header("token", token);


        Cookie[] cookies = request.getCookies();
        if(ObjectUtil.isNull(cookies)) return;
        for (Cookie cookie: cookies) {
            if("token".equals(cookie.getName())){
                // 把TOKEN带到下服务（token消息加到头消息）
                requestTemplate.header("token", cookie.getValue());
            }
        }

    }

}
